﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using SharedClientDll;
using Shared.SoftMethod;
using Shared.Method;
using System.IO.Ports;
using Ivi.Visa.Interop;

namespace WindowsFormsBobWrite
{
    public partial class FormWrite : Form
    {
        //private DataTable _modemDevice = null;
        private string _type = null;
        private List<Shared.Model.Device_Data> _listDevices = null;

        private string _localIp = null;
        private string _serverIp = null;
        private int _localPort = 0;
        //private int _serverPort = 23;

        private int _portOffset = DateTime.Now.Second;

        private SerialPort _serial = null;
        private FormattedIO488 _myN1010A;

        private double _powerOffset = 0;
        private double _erLow = 10;
        private double _erHigh = 18;
        private double _powerLow = 1.2;
        private double _powerHigh = 4;
        private double _powerTarget = 3.0;//功率期望值
        private double _erTarget = 13.0;//消光比期望值

        public FormWrite()
        {
            InitializeComponent();
        }

        private void FormWrite_Load(object sender, EventArgs e)
        {

            #region telnet third
            //Task.Run(() =>
            //{
            //    YcdTelnetThird telnet3 = new YcdTelnetThird("192.168.1.1", "192.168.1.213", 32345);
            //    telnet3.OnReceive += Tel_OnReceive;
            //    telnet3.Connect();
            //    BobBase.WriteReg(telnet3, 0x51, 0x7F, 0x04);
            //    List<byte> table4 = BobBase.ReadReg(telnet3, 0x51, 0x80, 0xE8);
            //    List<int> tlut4 = BobBase.Table2Tlut(table4);
            //    List<byte> table4new = BobBase.Tlut2Table(tlut4);

            //    if (table4.SequenceEqual(table4new))
            //    {
            //        MessageBox.Show("equal");
            //    }

            //    telnet3.Send("exit");
            //    telnet3.Close();
            //});

            //return;

            //double mw = BobBase.DBm2mW(3.45);

            #endregion

            _type = AppSetting.GetValue("SoftwareType");

            _localIp = AppSetting.GetValue("LocalIp");
            _serverIp = AppSetting.GetValue("ServerIp");

            int.TryParse(AppSetting.GetValue("LocalPort"), out _localPort);
            //int.TryParse(Shared.Method.AppSetting.GetValue("ServerPort"), out _serverPort);


            BobBase.OnReturnString += BobBase_OnReturnString;

            if (_type == "1")
            {
                this.Text = "广电BOB信息写入专用软件";
                this.label1.Text = "扫描BOSA";

                Client.MethodWcf.KEY = "RssPmq&AwYcc7<98Bux";
            }
            else if (_type == "2")
            {
                this.Text = "广电基础信息写入软件";
                this.label1.Text = "扫描MAC";

                //加载EXCEL文件
                OpenFileDialog open = new OpenFileDialog();
                open.ShowDialog();

                if (open.FileName.Contains(".xlsx") == false)
                {
                    MessageBox.Show("加载Excel文件失败");
                    Application.Exit();
                }

                DataTable modemDevice = YcdExcelStatic.ExcelToTable(open.FileName, out string msg);

                _listDevices = JsonConvert.DeserializeObject<List<Shared.Model.Device_Data>>(JsonConvert.SerializeObject(modemDevice));

                SoftShared.AppendText(this, this.richTextBoxMsg, msg);

                if (modemDevice == null)
                {
                    MessageBox.Show("加载Excel文件失败");
                    Application.Exit();
                }
            }
            else if (_type == "3")
            {
                this.Text = "广电BOB检查软件";

                double.TryParse(AppSetting.GetValue("PowerOffset"), out _powerOffset);
                double.TryParse(AppSetting.GetValue("ErLow"), out _erLow);
                double.TryParse(AppSetting.GetValue("ErHigh"), out _erHigh);
                double.TryParse(AppSetting.GetValue("ErTarget"), out _erTarget);

                double.TryParse(AppSetting.GetValue("PowerLow"), out _powerLow);
                double.TryParse(AppSetting.GetValue("PowerHigh"), out _powerHigh);
                double.TryParse(AppSetting.GetValue("PowerTarget"), out _powerTarget);

                this.label1.Visible = false;
                this.textBoxEnter.Visible = false;

                string localComName = AppSetting.GetValue("LocalCom");
                string ioAddr = AppSetting.GetValue("IoAddr");

                try
                {
                    _serial = PortBaseClass.GetNewSerialPort(9600, localComName, 8, out string msg);
                    SoftShared.AppendText(this, this.richTextBoxMsg, msg);

                    _myN1010A = new FormattedIO488Class();
                    ResourceManager manager = new ResourceManager();


                    _myN1010A.IO = (IMessage)manager.Open(ioAddr);
                    _myN1010A.IO.Timeout = 20000;

                    _myN1010A.IO.TerminationCharacter = 10;
                    _myN1010A.IO.TerminationCharacterEnabled = true;

                    _myN1010A.WriteString("*CLS", true);
                    _myN1010A.WriteString("*IDN?", true);

                    SoftShared.AppendText(this, this.richTextBoxMsg, _myN1010A.ReadString());
                    Application.DoEvents();
                }
                catch(Exception ex)
                {
                    SoftShared.AppendText(this, this.richTextBoxMsg, ex.ToString());
                }

                Task.Run(() =>
                {
                    while (true)
                        try
                        {
                            RunInspectBobThird();
                        }
                        catch (Exception ex)
                        {
                            SoftShared.AppendText(this, this.richTextBoxMsg, ex.ToString());
                        }
                });
            }
            else
            {
                MessageBox.Show("软件类型配置错误，即将关闭");
                Application.Exit();
            }

        }

        private void BobBase_OnReturnString(string obj)
        {
            Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, obj);
        }

        private void RichTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }

        private async void  TextBoxBOSA_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.textBoxEnter.ReadOnly) return;
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                string enter = this.textBoxEnter.Text.Trim();
                if (string.IsNullOrEmpty(enter)) return;

                this.textBoxEnter.ReadOnly = true;

                if (_type == "1")
                {
                    //await Task.Run(()=>RunWriteBob(enter));
                    await Task.Run(()=>RunWriteBobThird(enter));
                }
                else if (_type == "2")
                {
                    await Task.Run(()=>RunWriteMsg(enter));
                }

                this.textBoxEnter.ReadOnly = false;
                this.textBoxEnter.Clear();
                this.textBoxEnter.Focus();
                //this.richTextBoxMsg.Clear();
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'z')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'Z')
                || (e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "只能输入数字和字母");
                e.Handled = true;
            }
        }

        private void RunWriteMsg(string enter)
        {
            //从表中获取数据
            Shared.Model.Device_Data data = _listDevices.Where(a => a.MACAddr == enter).FirstOrDefault();
            if (data == null)
            {
                SoftShared.AppendText(this,this.richTextBoxMsg,"未能获得Device");
                SoftShared.SetControl(this, this.labelState, "获取Device失败", Color.Red);
                return;
            }

            YcdTelnetSecond tel = GetTelnet();

            if (tel == null || tel.Connected == false) return;

            //写信息
            bool writeReg = tel.SendAndRecv($"flash set HW_CWMP_PRODUCTCLASS {data.DeviceType}", $"={data.DeviceType}", out string allMsg);
            SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            writeReg = tel.SendAndRecv($"flash set ELAN_MAC_ADDR {data.MACAddr}", $"={data.MACAddr}", out allMsg);
            SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            writeReg = tel.SendAndRecv($"flash set USER_PASSWORD {data.WedPassword}", $"={data.WedPassword}", out allMsg);
            SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            if (data.PONType == "STIA")
                writeReg = tel.SendAndRecv($"flash set PON_MODE 1", "PON_MODE=1", out allMsg);
            else
                writeReg = tel.SendAndRecv($"flash set PON_MODE 2", "PON_MODE=2", out allMsg);

            SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            writeReg = tel.SendAndRecv($"flash set GPON_SN {data.XPON_SN}", $"={data.XPON_SN}", out allMsg);
            SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            SoftShared.SetControl(this, this.labelState, "PASS", Color.Green);

            tel.Send("exit");
            tel.Close();
        }

        private void RunWriteBobThird(string enter)
        {
            //写BOB信息
            var listBosa = Client.MethodWcf.SelectJsonClient<List<Shared.Model.BOSA_DATA>>($"SELECT * FROM BOSA_DATA WHERE SN='{enter}'");
            if (listBosa == null || listBosa.Count == 0)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "无BOSA信息");
                return;
            }

            var listPass = Client.MethodWcf.SelectJsonClient<List<Shared.Model.BOB_DEFAULT>>(
                $"SELECT * FROM Modem.dbo.BOB_DEFAULT WHERE PON_TYPE='{listBosa[0].DeviceType}' AND BG_MIN<{listBosa[0].Imo_mA * 1000} AND BG_MAX>{listBosa[0].Imo_mA * 1000}  AND POWER_MAX>{listBosa[0].Po_dBm} AND POWER_MIN<{listBosa[0].Po_dBm} ORDER BY TABLE_ID DESC");

            if (listPass == null || listPass.Count == 0)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "查无经验值");
                return;
            }

            YcdTelnetThird tel = GetTelnetThird();
            BobBase.EnterDiag(tel);

            if (tel == null || tel.Connected == false)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "Telnet失败");
                return;
            }

            //SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            SoftShared.AppendText(this, this.richTextBoxMsg, "写入BOB数据，预计需要1分钟");

            BobControl.InitBobReg(tel);

            bool writeResult = true;
            for (int i = 0; i < listPass.Count; i++)
            {
                BobBase.WriteReg(tel, 0x51, 0x7F, (byte)listPass[i].TABLE_ID);
                BobBase.WriteReg(tel, "51", 0x80, 0xE8, listPass[i].CONTEXT);
            }
            BobBase.ExitDiag(tel);

            tel.Send($"flash set GPON_SN FHTT002460E2");

            tel.Send("flash default cs");
            //SoftShared.AppendText(this, this.richTextBoxMsg, allMsg);

            System.Threading.Thread.Sleep(3000);

            tel.Send("exit");

            tel.Close();

            if (writeResult)
                SoftShared.SetControl(this, this.labelState, "PASS", Color.Green);
            else
                SoftShared.SetControl(this, this.labelState, "FAIL", Color.Red);

        }

        private void RunInspectBob()
        {
            WaitForModemExit();

            YcdTelnetSecond tel = GetTelnet();

            if (tel == null || tel.Connected == false) return;

            tel.SendAndRecv("diag register set 0x22094 0x40af", "command:#", out string msg);
            SoftShared.AppendText(this, this.richTextBoxMsg, msg);

            tel.SendAndRecv("diag register set 0x22098 0x1", "command:#", out msg);
            SoftShared.AppendText(this, this.richTextBoxMsg, msg);

            tel.Send("exit");
            tel.Close();

            System.Threading.Thread.Sleep(2000);

            double power = GetPowerFromSerial();

            if (power+_powerOffset > _powerLow && power+_powerOffset <= _powerHigh)
            {
                SoftShared.SetControl(this, this.labelState, "光功率合格", Color.Green);
            }
            else
            {
                SoftShared.SetControl(this, this.labelState, "光功率不合格", Color.Red);
                return;
            }

            double erDb = GetErFromSerial();

            //_myN1010A.IO.Close();
            if (erDb >= _erLow && erDb <= _erHigh)
            {
                SoftShared.SetControl(this, this.labelState, "PASS", Color.Green);
            }
            else
            {
                SoftShared.SetControl(this, this.labelState, "消光比不合格", Color.Red);
            }
        }

        private void RunInspectBobThird()
        {
            WaitForModemExit();

            YcdTelnetThird tel = GetTelnetThird();

            if (tel == null || tel.Connected == false) return;

            BobBase.EnterDiag(tel);

            //开启长发光
            tel.Send("register set 0x22094 0x40af");
            tel.Send("register set 0x22098 0x1");
            //等待长发光开启
            System.Threading.Thread.Sleep(1000);

            bool checksum = false;
            //goto jump;
            //获取功率值\
            double power = GetPowerFromSerial();


            bool powerPass;
            bool erPass = false ;
            if (power + _powerOffset > _powerLow && power + _powerOffset <= _powerHigh)
            {
                SoftShared.SetControl(this, this.labelState, "光功率合格", Color.Green);
                powerPass = true;
            }
            else
            {
                SoftShared.SetControl(this, this.labelState, "光功率不合格", Color.Red);
                powerPass = RunDebugPower(tel, power);
                checksum = true;
            }

            //goto jump;
            double erDb = GetErFromSerial();

            //_myN1010A.IO.Close();
            if (erDb >= _erLow && erDb <= _erHigh)
            {
                SoftShared.SetControl(this, this.labelState, "消光比合格", Color.Green);
                erPass = true;
            }
            else
            {
                SoftShared.SetControl(this, this.labelState, "消光比不合格", Color.Red);
                erPass = RunDebugEr(tel, erDb);
                checksum = true;
            }       

            if (checksum)
            {
                BobControl.CheckSum(tel);
            }

            if (powerPass && erPass)
            {
                SoftShared.SetControl(this, this.labelState, "PASS", Color.Green);
            }
            else
            {
                SoftShared.SetControl(this, this.labelState, "FAIL", Color.Red);
            }

            BobBase.ExitDiag(tel);

            tel.Send("exit");
            tel.Close();

        }
        /// <summary>
        /// 调试POWER，发射光功率
        /// </summary>
        /// <param name="telnetThird">telnet第三版</param>
        /// <param name="power0_dBm">光功率，没有offset</param>
        private bool RunDebugPower(YcdTelnetThird telnetThird, double power0_dBm)
        {
            if (power0_dBm < -10)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "光功率太小，无法调试");
                return false;
            }
            //选择表3
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x03);

            //关闭温度查找表
            BobBase.WriteReg(telnetThird, 0x51, 0x82, 0x89);

            //如果光功率大于最大光功率的30%，则减小MPD的值0x83改为0
            if (power0_dBm + _powerOffset > 5)
            {
                BobBase.WriteReg(telnetThird, 0x51, 0x83, 0x0);
                System.Threading.Thread.Sleep(500);
                power0_dBm = GetPowerFromSerial();
            }


            //计算DA值
            List<byte> daBytes = BobBase.ReadReg(telnetThird, 0x51, 0x8C, 0x8D);
            int daInt = BobBase.Bytes2Int(daBytes.ToArray(), true);
            byte[] daNewBytes = BobBase.Int2Bytes((int)(daInt * 1.4), true);//1.25倍da p1set的值
            daNewBytes[1] = (byte)(daNewBytes[1] + (daBytes[1] & 0xFC));
            BobBase.WriteReg(telnetThird, 0x51, 0x8C, 0x8D, daNewBytes);

            System.Threading.Thread.Sleep(500);

            double power1_dBm = GetPowerFromSerial();

            //计算power对应的mw
            double power0_mW = BobBase.DBm2mW(power0_dBm + _powerOffset);
            double power1_mW = BobBase.DBm2mW(power1_dBm + _powerOffset);
            double powerTarget_mW = BobBase.DBm2mW(_powerTarget);

            int daTarget = (int)((powerTarget_mW - power0_mW) * (0.4 * daInt) / (power1_mW - power0_mW)) + daInt;

            //写DA值
            BobBase.WriteReg(telnetThird, 0x51, 0x8C, 0x8D, BobBase.Int2Bytes(daTarget, true));

            //写Bias数据
            List<byte> biasR = BobBase.ReadReg(telnetThird, 0x51, 0xDE, 0xDF);
            BobBase.WriteReg(telnetThird, 0x51, 0x85, 0x86, biasR.ToArray());

            //写Ibias温度查找表
            WriteBiasLut(telnetThird);

            //读写表三
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x03);
            //打开温度查找表
            BobBase.WriteReg(telnetThird, 0x51, 0x82, 0xC9);

            //System.Threading.Thread.Sleep(1000);

            //检查POWER是否合格
            bool powerPass = false;
            double powerNow = GetPowerFromSerial();

            if (powerNow + _powerOffset >= _powerLow && powerNow + _powerOffset <= _powerHigh)
            {
                powerPass = true;
            }

            return powerPass;
        }
        //写Bias LUT
        private void WriteBiasLut(YcdTelnetThird telnetThird)
        {
            List<byte> biasDacBytes = BobBase.ReadReg(telnetThird, 0x51, 0xDE, 0xDF);
            int biasDacInt = BobBase.Bytes2Int(biasDacBytes.ToArray(), true);

            byte tempAdc = BobBase.ReadReg(telnetThird, 0x51, 0xE9);
            int index = (tempAdc - 65) >> 1;

            //读写表4
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x04);
            List<byte> table4 = BobBase.ReadReg(telnetThird, 0x51, 0x80, 0xE8);

            //计算真实的BLUT4
            List<int> btlut4 = BobBase.Table2Tlut(table4);

            int biasTlutInt = btlut4[index];

            if (biasDacInt - biasTlutInt < -50 && biasDacInt - biasTlutInt > 50)
            {
                //需要进行Tlut缩放操作
                double k = (double)biasDacInt / biasTlutInt;
                for(int i = 0; i < btlut4.Count; i++)
                {
                    btlut4[i] = (int)(k * btlut4[i]);
                }

                table4 = BobBase.Tlut2Table(btlut4);

                BobBase.WriteReg(telnetThird, 0x51, 0x80, 0xE8, table4.ToArray());
            }

        }
        //调试消光比
        private bool RunDebugEr(YcdTelnetThird telnetThird,double er_dBm)
        {
            if (er_dBm < 5)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "消光比太小，无法调试");
                return false;
            }

            //选择表3
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x03);

            //关闭温度查找表
            BobBase.WriteReg(telnetThird, 0x51, 0x82, 0x89);

            //查询消光比与目标光功率得比值
            List<byte> moddacBytes = BobBase.ReadReg(telnetThird, 0x51, 0x87, 0x88);
            int moddacInt = BobBase.Bytes2Int(moddacBytes.ToArray(), true);
            int moddacIntTarget = (int)(_erTarget / er_dBm * moddacInt);

            //根据比值修改DA得值
            byte[] moddacBytesTarget = BobBase.Int2Bytes(moddacIntTarget, true);
            BobBase.WriteReg(telnetThird, 0x51, 0x87, 0x88, moddacBytesTarget);

            //完成后修改MOD LUT表
            WriteModLut(telnetThird, moddacIntTarget);
            //选择表3
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x03);
            //打开温度查找表
            BobBase.WriteReg(telnetThird, 0x51, 0x82, 0xC9);

            double erDb = GetErFromSerial();

            if (erDb >= _erLow && erDb <= _erHigh)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //写Mod 温度查找表
        private void WriteModLut(YcdTelnetThird telnetThird,int modDacInt)
        {
            byte tempAdc = BobBase.ReadReg(telnetThird, 0x51, 0xE9);
            int index = (tempAdc - 65) >> 1;

            //读写表5
            BobBase.WriteReg(telnetThird, 0x51, 0x7F, 0x05);
            List<byte> table5 = BobBase.ReadReg(telnetThird, 0x51, 0x80, 0xE8);

            //计算真实的BLUT5
            List<int> btlut5 = BobBase.Table2Tlut(table5);

            int modTlutInt = btlut5[index];

            //需要进行Tlut缩放操作
            double k = (double)modDacInt / modTlutInt;
            for (int i = 0; i < btlut5.Count; i++)
            {
                btlut5[i] = (int)(k * btlut5[i]);
            }

            table5 = BobBase.Tlut2Table(btlut5);

            BobBase.WriteReg(telnetThird, 0x51, 0x80, 0xE8, table5.ToArray());

        }

        private YcdTelnetSecond GetTelnet()
        {
            //ping
            //显示正在测试当中
            //SetTestState(true, "WAITFOR");
            SoftShared.SetControl(this, this.labelState, "WAITFOR", Color.Black);

            //PING光猫
            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _serverIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }
                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "未能成功PING通光猫");
                SoftShared.SetControl(this, this.labelState, "PING失败", Color.Red);
                return null;
            }

            //尝试5次1秒一次
            SoftShared.SetControl(this, this.labelState, "TESTING", Color.Black);

            SoftShared.SetControl(this, this.richTextBoxMsg, string.Empty);

            ////初始化telnet
            YcdTelnetSecond tel = null;
            for (int i = 0; i < 5; i++)
            {
                //初始化telnet
                if (_portOffset >= 800) _portOffset = 0;
                _portOffset++;

                tel = new YcdTelnetSecond(_serverIp, _localIp, _localPort + _portOffset);
                tel.Connect();

                if (tel == null)
                {
                    SoftShared.AppendText(this, this.richTextBoxMsg, "TELNET光猫失败");
                }
                else
                {
                    break;
                }

                System.Threading.Thread.Sleep(5000);
            }

            return tel;
        }

        private YcdTelnetThird GetTelnetThird()
        {
            //ping
            //显示正在测试当中
            //SetTestState(true, "WAITFOR");
            SoftShared.SetControl(this, this.labelState, "WAITFOR", Color.Black);

            //PING光猫
            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _serverIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }
                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "未能成功PING通光猫");
                SoftShared.SetControl(this, this.labelState, "PING失败", Color.Red);
                return null;
            }

            //尝试5次1秒一次
            SoftShared.SetControl(this, this.labelState, "TESTING", Color.Black);

            SoftShared.SetControl(this, this.richTextBoxMsg, string.Empty);

            ////初始化telnet
            YcdTelnetThird tel = null;

            for (int i = 0; i < 2; i++)
            {
                //初始化telnet
                if (_portOffset >= 800) _portOffset = 0;
                _portOffset++;

                tel = new YcdTelnetThird(_serverIp, _localIp, _localPort + _portOffset);
                tel.Connect();

                if (tel == null)
                {
                    SoftShared.AppendText(this, this.richTextBoxMsg, "TELNET光猫失败");
                }
                else
                {
                    break;
                }

                System.Threading.Thread.Sleep(5000);
            }

            tel.OnReceive += Tel_OnReceive;

            return tel;
        }

        private void Tel_OnReceive(string obj)
        {
            SoftShared.AppendText(this, this.richTextBoxMsg, obj);
        }

        private void WaitForModemExit()
        {
            //判断光猫断开连接
            SoftShared.AppendText(this, this.richTextBoxMsg, "等待断开光猫");

            while (PingBaseClass.PingTest(_localIp, _serverIp) == true) System.Threading.Thread.Sleep(2000);

            SoftShared.SetControl(this, this.richTextBoxMsg, "等待光猫连接");
        }

        private void FormWrite_FormClosed(object sender, FormClosedEventArgs e)
        {
            _myN1010A?.IO?.Close();
        }

        private double GetPowerFromSerial()
        {
            //获取power1_dbm
            if (_serial == null)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "未能获得串口连接");
                return -1000;
            }

            PortBaseClass.SerialPortSendAndRecv(_serial, ":FETC:MEAS:VAL?", "\r\n", out string msg);
            SoftShared.AppendText(this, this.richTextBoxMsg, "光功率：" + msg);

            float.TryParse(msg.Trim(), out float power_dBm);

            return power_dBm;
        }

        private double GetErFromSerial()
        {
            if (_myN1010A == null)
            {
                SoftShared.SetControl(this, this.labelState, "FAIL", Color.Red);
                return 0;
            }

            //Select Eye/Mask Mode and Autoscale
            _myN1010A.WriteString(":ACQ:RUN", true);
            _myN1010A.WriteString(":SYSTem:MODE EYE", true);
            _myN1010A.WriteString(":SYSTem:AUToscale", true);
            _myN1010A.WriteString("*OPC?", true);
            //SoftShared.AppendText(this, this.richTextBoxMsg, _myN1010A.ReadString());
            string complate = _myN1010A.ReadString();

            //Define and Load Mask File
            _myN1010A.WriteString(":MTESt:LOAD:FNAMe \"C:\\Program Files\\Agilent\\FlexDCA\\Demo\\Masks\\SONET_SDH\\002.48832 - STM016_OC48.mskx\"", true);
            _myN1010A.WriteString(":MTESt:LOAD", true);

            //set acquisition limit
            _myN1010A.WriteString(":ACQuire:CDISplay", true);
            _myN1010A.WriteString(":LTESt:ACQuire:CTYPe:WAVeforms 100", true);
            _myN1010A.WriteString(":LTESt:ACQuire:STATe ON", true);
            _myN1010A.WriteString("*OPC?", true);
            //SoftShared.AppendText(this, this.richTextBoxMsg, _myN1010A.ReadString());
            complate = _myN1010A.ReadString();

            //setup mask margin
            _myN1010A.WriteString(":MTESt:MARGin:STATe ON", true);
            _myN1010A.WriteString(":MTESt:MARGin:METHod AUTO", true);
            _myN1010A.WriteString(":MTESt:MARGin:AUTO:METHod HRATio", true);
            _myN1010A.WriteString(":MTESt:MARGin:AUTO:HRATio 5e-5", true);
            //complate = _myN1010A.ReadString();

            _myN1010A.WriteString(":MEASure:EYE:ERATio", true);
            _myN1010A.WriteString(":MEASure:EYE:ERATio?", true);
            string er = _myN1010A.ReadString();
            //_myN1010A.WriteString(":MEASure:EYE:AMPLitude", true);

            double.TryParse(er.Trim(), out double erDb);

            SoftShared.AppendText(this, this.richTextBoxMsg, $"ER:{er.Trim()},ER_DB:{erDb}");

            _myN1010A.WriteString(":LTESt:ACQuire:STATe OFF", true);

            Application.DoEvents();

            return erDb;
        }
    }
}
